<template>
  <el-dialog title="选择设备" v-model="visibleMachine" width="60%" append-to-body>
    <el-row>
      <el-col :span="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" size="small">
          <el-form-item label="设备名称" prop="machineName">
            <el-input v-model="queryParams.machineName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="设备编号" prop="machineId">
            <el-input v-model="queryParams.machineId" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="设备标签" prop="machineTag">
            <el-select v-model="queryParams.machineTag" clearable placeholder="请选择">
              <el-option
                v-for="item in tagOptions"
                :key="item.tagId"
                :label="item.tagName"
                :value="item.tagId"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleSearchResect">重置</el-button>
            <el-button type="primary" @click="getList('search')">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <!--点位数据-->
      <el-col :span="5" :xs="24">
        <div class="position-box">
          <el-radio-group v-model="positionTypeId" @change="getPositionType(positionTypeId)">
            <el-radio
              v-for="(item, index) in positionTypeOptions"
              :key="index"
              :label="item.positionTypeId"
              :value="item.positionTypeId"
              >{{ item.typeName }}</el-radio
            >
          </el-radio-group>
        </div>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-table
          :data="tableListAll"
          max-height="580"
          @selection-change="handleSelectionChange"
          ref="tableAllRef"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            label="设备编号"
            align="center"
            prop="machineId"
            :show-overflow-tooltip="true"
            min-width="90"
          />
          <el-table-column
            label="设备名称"
            align="center"
            prop="machineName"
            :show-overflow-tooltip="true"
            min-width="90"
          />
          <el-table-column
            label="设备标签"
            align="center"
            prop="machineTag"
            :show-overflow-tooltip="true"
            min-width="90"
          />
          <el-table-column
            label="投放地点"
            align="center"
            prop="positionAddr"
            :show-overflow-tooltip="true"
            min-width="90"
          />
        </el-table>
      </el-col>
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visibleMachine = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelected" :loading="loadingSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, reactive, watch, onMounted, nextTick } from 'vue'
import { getMachineList, pushVersion } from '@/api/advert'
import { getDeviceTagList } from '@/api/device/tag'
import { getPointTypeList } from '@/api/organization/pointType'

const props = defineProps({
  operType: {
    type: String,
    default: 'add'
  }
})
const emit = defineEmits(['updateList'])
const { proxy } = getCurrentInstance()
const { device_ad_type, device_ad_position } = proxy.useDict('device_ad_type', 'device_ad_position')
const visible = ref(false)
const loadingSubmit = ref(false)
const versionRef = ref()

const rules = {
  machineId: [{ required: true, message: '设备机器不能为空', trigger: ['blur', 'change'] }],
  adId: [{ required: true, message: '广告不能为空', trigger: ['blur', 'change'] }],
  adType: [{ required: true, message: '广告类型不能为空', trigger: ['blur', 'change'] }]
}

//** 设备标签 && 点位类型 && 广告列表 */
const tagOptions = ref([])
const positionTypeId = ref(null)
const positionTypeOptions = ref([])
function getOptions() {
  getDeviceTagList({ pageNum: 1, pageSize: 500 }).then((res) => {
    tagOptions.value = res.rows
  })
  getPointTypeList({ pageNum: 1, pageSize: 500 }).then((r) => {
    positionTypeOptions.value = r?.data ?? r?.rows
  })
}

//** 设备列表 */
const queryParams = ref({
  machineTag: null,
  positionTypeId: null,
  machineName: null,
  machineId: null
})
const tableListAll = ref([])
const tableList = ref([])
function getList(search) {
  let selectedIds = selected.value.map((item) => item.machineId)
  getMachineList(queryParams.value).then((res) => {
    tableListAll.value = res.data
    if (search === 'search') {
      setTimeout(() => {
        tableListAll.value.forEach((ele) => {
          if (selectedIds.includes(ele.machineId)) {
            tableAllRef.value.toggleRowSelection(ele, true)
          }
        })
      }, 100)
    }
  })
}
function handleSearchResect() {
  queryParams.value.machineTag = null
  queryParams.value.machineName = null
  queryParams.value.machineId = null
  positionTypeId.value = null
  queryParams.value.positionTypeId = null
  getList('search')
}
function getPositionType(positionTypeId) {
  queryParams.value.positionTypeId = positionTypeId
  getList('search')
}

const tableAllRef = ref()
//** 选择设备 */
const visibleMachine = ref(false)
function handleAddFileColumn() {
  handleSearchResect()
  let selectedIds = tableList.value.map((item) => item.machineId)
  tableListAll.value.forEach((row) => {
    if (selectedIds.includes(row.machineId)) {
      nextTick(() => {
        tableAllRef.value.toggleRowSelection(row, true)
      })
    } else {
      nextTick(() => {
        tableAllRef.value.toggleRowSelection(row, false)
      })
    }
  })
}
const selected = ref([])
const handleSelectionChange = (val) => {
  selected.value = val
}
const confirmSelected = () => {
  loadingSubmit.value = true
  tableList.value = selected.value

  let params = {
    appVersionNo: currentId.value,
    machineId: tableList.value.map((ele) => ele.machineId)
  }
  pushVersion(params).then(
    (res) => {
      proxy.$modal.msgSuccess('推送成功')
      emit('updateList')
      tableList.value = []
      visibleMachine.value = false
    },
    (error) => {
      loadingSubmit.value = false
    }
  )
}

//** init */
const currentId = ref()
function show(type, id) {
  getOptions()
  selected.value = []
  loadingSubmit.value = false
  tableList.value = []
  currentId.value = id
  handleAddFileColumn()
  getList()
  visibleMachine.value = true
}

defineExpose({
  show
})
</script>

<style lang="scss" scoped>
:deep(.el-radio) {
  width: 100%;
}
.position-box {
  background-color: #f2f2f2;
  width: 100%;
  min-height: 300px;
  max-height: 600px;
  padding: 8px;
  overflow-y: scroll;
  overflow-x: hidden;
}
</style>
